package br.com.farmabid.component;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import javax.enterprise.event.Observes;
import javax.websocket.CloseReason;
import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.apache.log4j.Logger;

import br.com.farmabid.oportunidade.Oportunidade;


@ServerEndpoint(value="/wsOportunidade",
		encoders={OportunidadeEncoder.class},
	    decoders={OportunidadeDecoder.class})
public class WsEndpoint {
	private Logger logger = Logger.getLogger(this.getClass().getName());
	static Set<Session> peers = Collections.synchronizedSet(new HashSet<Session>());
	
	@OnOpen
    public void onOpen(Session session) {
        logger.info("Connected ... " + session.getId());
        peers.add(session);
    }

	public void observaOportunidade(@Observes Oportunidade localizacao){
		try {
             //Send updates to all open WebSocket sessions for this match 
            for (Session session : peers) {
                if (session.isOpen()){
                      session.getBasicRemote().sendObject(localizacao);       
                }
            }
          } catch (IOException | EncodeException e) {
        	  e.printStackTrace();
          }
	}
 
    @OnMessage
    public String onMessage(String message, Session session) {
    	System.out.println(message);
    	peers.add(session);
        return "teste";
    }
 
    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        logger.info(String.format("Session %s closed because of %s", session.getId(), closeReason));
    }
	
} 